import passwordHtml from 'ngtemplate!html!../../../tpls/validation/password.html';

class ModifypassController {
    constructor($rootScope, $scope, $state, $cookieStore, $timeout, ngDialog, dialogService, UserService){
        
        var vm = this;

        vm.$rootScope    = $rootScope;
        vm.$state        = $state;
        vm.$cookieStore  = $cookieStore;
        vm.$timeout      = $timeout;
        vm.ngDialog      = ngDialog;
        vm.dialogService = dialogService;
        vm.UserService   = UserService;

        vm.passwordHtml = passwordHtml;
        
        // 显示提示
        vm.valid = true;

        // 初始化表单数据
        vm.user = {
            oldpass: '', 
            newpass: '', 
            confirmpass: ''
        }

        // 监听确认密码、判断两次输入是否一直
        $scope.$watch(angular.bind(vm, () => vm.user.confirmpass ), (newValue, oldValue) => {
            if (newValue) {
                if (newValue==vm.user.newpass) {
                    vm.valid = false;
                } else {
                    vm.valid = true;
                }
            }
        });

    }

    // 提交表单
    submitForm(isValid) {
        
        var vm = this;

        // 验证失败
        if (!isValid) {

            if (!vm.user.oldpass) {
                vm.dialogService.error('旧密码未填写')
            } else if (!vm.user.newpass) {
                vm.dialogService.error('新密码未填写')
            } else if (!vm.user.confirmpass) {
                vm.dialogService.error('确认新密码未填写')
            }

        }

        // 验证成功
        if (isValid) {

            // 判断两次输入的密码不一致
            if (vm.user.newpass!=vm.user.confirmpass) {
                vm.dialogService.error('两次输入的密码不一致')
                return false;
            }

            // 禁用按钮
            vm.hide = true;

            // 拼接POST数据格式
            var params = {
                origpass: vm.user.oldpass,
                newpass: vm.user.newpass
            }

            console.log(params)

            // 修改密码
            vm.UserService.postChangepwd(params, vm.$cookieStore.get('access_token'))
            .then(data => {

                // 显示按钮
                vm.hide = false;
                
                // 成功调用
                data.code==0&&vm.dialogService.success('密码修改成功', 'loginindex.login');

                // 调用失败, 提示用户
                (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);

                // 登录信息已过期, 请重新登录
                data.code==-1001&&vm.dialogService.error(data.message, true);

                console.log(data)
            }, error => {
                console.log('error')
            })

        }

        return false;
    }
}

ModifypassController.$inject = ['$rootScope', '$scope', '$state', '$cookieStore', '$timeout', 'ngDialog', 'dialogService', 'UserService']; 

export default ModifypassController;